<template>
  <div id="zcbi-box">
    <div style="width: 100%;height: 100%;position: absolute;">
      <L7DarkMap @mapLoaded="handleMapLoaded" :zoom="12">
        <div id="zcbi-toolbar"
          style="position: absolute;top: 110px;left: 36.5%;z-index: 999999;margin: 5px;padding: 5px;background-color: #204f86;color: #FFFFFF;">
          计量分区
          <el-switch style="margin-right: 8px;"
                     v-model="polygonLayersVisible"
                     active-color="#13ce66"
                     inactive-color="#ff4949" @change="handlePolygonLayersVisibleChange">
          </el-switch>
          供水管网
          <el-switch style="margin-right: 8px;"
                     v-model="pipeNetworkVisible"
                     active-color="#13ce66"
                     inactive-color="#ff4949" @change="handlePipeNetworkVisibleChange">
          </el-switch>
          考核表
          <el-switch style="margin-right: 8px;"
                     v-model="examineTerminalMarkerVisible"
                     active-color="#13ce66"
                     inactive-color="#ff4949" @change="handleExamineTerminalMarkerVisibleChange">
          </el-switch>
          大用户
          <el-switch style="margin-right: 8px;"
                     v-model="dyhTerminalMarkerVisible"
                     active-color="#13ce66"
                     inactive-color="#ff4949" @change="handleDyhTerminalMarkerVisibleChange">
          </el-switch>
        </div>

        <div style="position: fixed;bottom: 10px;right: 10px;width: 180px;height: 32px;z-index: 10000;">
          <img :src="require(`@/assets/leakage/bi/legend.png`)" width="180" height="32" alt="">
        </div>
      </L7DarkMap>
    </div>

    <div id="zcbi-header1" class="header">
      <div class="bg"></div>
      <div class="header-home"
           @click="handleHomeIconClick">
        <i class="el-icon-s-home" style="margin-right: 5px;"></i>后台管理
      </div>
    </div>

    <div id="zcbi-header2" class="header-foot">{{ store.getters.deptName }}</div>

    <div id="zcbi-box1" style="position: absolute;top: 12%;left: 10px;z-index: 11000;">
      <div class="box-container">
        <div style="width: 100%;display: flex;justify-content: space-between;">
          <div class="box-head">宁西街 - 数据总览</div>
          <div style="margin-top: 10px;">
          </div>
        </div>

        <div style="padding: 10px;">
          <div v-if="overviewShowType==='monthly'"
               style="width: 100%;display: flex;justify-content: space-between;flex-wrap: wrap;">
            <AssetsItem v-for="item in nxOverviewMonthlyOptions" :text="item.text" :value="item.value"
                        :changeStyle="item.changeStyle"></AssetsItem>
          </div>
        </div>
      </div>

      <div class="box-container">
        <div style="width: 100%;display: flex;justify-content: space-between;">
          <div class="box-head">供水变化趋势</div>
        </div>
        <div id="nx-water-supply-chart" style="width: 100%;height: 320px;margin-top: 10px;"></div>
      </div>

      <div class="box-container">
        <div style="width: 100%;display: flex;justify-content: space-between;">
          <div class="box-head">上月绩效统计</div>
          <div style="margin-top: 10px;display: flex;align-items: center;">
            <button :class="nxKpiShowType==='dfq'?'custom-btn custom-btn-active':'custom-btn'"
                    @click="nxKpiShowType='dfq'">大分区
            </button>
            <button :class="nxKpiShowType==='dma'?'custom-btn custom-btn-active':'custom-btn'"
                    @click="nxKpiShowType='dma'">DMA
            </button>
          </div>
        </div>

        <div style="padding: 10px;">
          <dv-scroll-board v-if="nxKpiShowType==='dfq'" :config="nxDfqKpiConfig" style="width: 100%;height:220px"/>
          <dv-scroll-board v-if="nxKpiShowType==='dma'" :config="nxDmaKpiConfig" style="width: 100%;height:220px"/>
        </div>
      </div>
    </div>

    <div id="zcbi-box2" style="position: absolute;top: 12%;right: 10px;z-index: 11000;">
      <div class="box-container">
        <div style="width: 100%;display: flex;justify-content: space-between;">
          <div class="box-head">朱村街 - 数据总览</div>
          <div style="margin-top: 10px;">
          </div>
        </div>

        <div style="padding: 10px;">
          <div v-if="overviewShowType==='monthly'"
               style="width: 100%;display: flex;justify-content: space-between;flex-wrap: wrap;">
            <AssetsItem v-for="item in zcOverviewMonthlyOptions" :text="item.text" :value="item.value"
                        :changeStyle="item.changeStyle"></AssetsItem>
          </div>
        </div>
      </div>

      <div class="box-container">
        <div style="width: 100%;display: flex;justify-content: space-between;">
          <div class="box-head">供水变化趋势</div>
        </div>
        <div id="zc-water-supply-chart" style="width: 100%;height: 320px;margin-top: 10px;"></div>
      </div>

      <div class="box-container">
        <div style="width: 100%;display: flex;justify-content: space-between;">
          <div class="box-head">上月绩效统计</div>
          <div style="margin-top: 10px;display: flex;align-items: center;">
            <button :class="zcKpiShowType==='dfq'?'custom-btn custom-btn-active':'custom-btn'"
                    @click="zcKpiShowType='dfq'">大分区
            </button>
            <button :class="zcKpiShowType==='dma'?'custom-btn custom-btn-active':'custom-btn'"
                    @click="zcKpiShowType='dma'">DMA
            </button>
          </div>
        </div>

        <div style="padding: 10px;">
          <dv-scroll-board v-if="zcKpiShowType==='dfq'" :config="zcDfqKpiConfig" style="width: 100%;height:220px"/>
          <dv-scroll-board v-if="zcKpiShowType==='dma'" :config="zcDmaKpiConfig" style="width: 100%;height:220px"/>
        </div>
      </div>
    </div>

    <TerminalDataDetailDialog ref="refTerminalDataDetailDialog"/>
  </div>
</template>

<script>
import moment from 'moment'
import screenfull from 'screenfull'
import L7DarkMap from '@/components/L7Maps/darkmap.vue'
import AssetsItem from "./components/AssetsItem.vue";
import {getZCOverviewData, getDfqKpiData, getDMAKpiData} from '@/api/leakage/biZbx'
import * as echarts from "echarts";
import {Marker, MarkerLayer, PolygonLayer, LineLayer, Popup} from "@antv/l7";
import * as turf from "@turf/turf";
import {listAllTerminals} from "@/api/leakage/terminalsInfo";
import TerminalDataDetailDialog from "@/views/leakage/components/TerminalDataDetailDialog.vue";
import store from "../../../store";
import {drawWmsLayer} from "@/components/L7Maps/util";
import {getZoneJoinTerminals} from "@/api/leakage/zoneJoin";
import {autoFit, keepFit} from '@/utils/autofit.js'

require('echarts/theme/macarons') // echarts theme

const colors = ['#3488fa', '#42d4ad', '#f0589d'];

const sumByKey = (arr, key) => {
  return arr.reduce((prev, cur) => {
    return parseFloat(prev) + parseFloat(cur[key])
  }, 0.00)
}

export default {
  components: {
    TerminalDataDetailDialog,
    L7DarkMap,
    AssetsItem
  },
  data() {
    return {
      mapScene: undefined,
      mapCenterFocused: false,
      terminalMarkerLayer: undefined,
      // 考核表图层
      examineTerminalMarkerLayer: undefined,
      // 考核表图层是否可见
      examineTerminalMarkerVisible: false,
      // 大用户图层
      dyhTerminalMarkerLayer: undefined,
      // 大用户表图层是否可见
      dyhTerminalMarkerVisible: false,
      // 管线图层
      pipeNetworkLayers: [],
      // 管线图层是否可见
      pipeNetworkVisible: true,
      // 面图层
      polygonLayers: [],
      polygonLayersVisible: true,
      layerOriginColorMap: {},
      nxWaterSupplyChart: undefined,
      zcWaterSupplyChart: undefined,
      isFullscreen: false,
      screenBottom: 95,
      timerHandler: null,
      currentTime: null,
      assetsOptions: [
        {text: '大分区数量（个）', key: 'dfq', value: 0, detailPath: '/settings/region/basicDfq'},
        {text: 'DMA数量（个）', key: 'dma', value: 0, detailPath: '/settings/region/basicDma'},
        {text: '大用户数量（个）', key: 'dyh', value: 0, detailPath: '/settings/region/basicDyh'},
        {text: '户表数量（个）', key: 'meter', value: 0, detailPath: '/device/terminalsXbInfo'},
      ],
      overviewAnnualOptions: [
        {text: '供水量（m³）', key: 'supplyQn', value: 0},
        {text: '售水量（m³）', key: 'saleQn', value: 0},
        {text: '无收益水量（m³）', key: 'freeQn', value: 0},
        {text: '产销差率（%）', key: 'cxclQn', value: 0},
      ],
      zcOverviewMonthlyOptions: [
        {text: '供水量（m³）', key: 'supply', value: 0, tbRate: '0.22', hbRate: '0.07'},
        {text: '售水量（m³）', key: 'sale', value: 0, tbRate: '0.34', hbRate: '0.05'},
        {text: '无收益水量（m³）', key: 'free', value: 0, tbRate: '0.11', hbRate: '0.1'},
        {text: '产销差率（%）', key: 'cxcl', value: 0, tbRate: '-0.09', hbRate: '0.02', changeStyle: true},
      ],
      nxOverviewMonthlyOptions: [
        {text: '供水量（m³）', key: 'supply', value: 0, tbRate: '0.22', hbRate: '0.07'},
        {text: '售水量（m³）', key: 'sale', value: 0, tbRate: '0.34', hbRate: '0.05'},
        {text: '无收益水量（m³）', key: 'free', value: 0, tbRate: '0.11', hbRate: '0.1'},
        {text: '产销差率（%）', key: 'cxcl', value: 0, tbRate: '-0.09', hbRate: '0.02', changeStyle: true},
      ],
      overviewShowType: 'monthly',
      nxKpiShowType: 'dfq',
      zcKpiShowType: 'dfq',
      selectedDfq: undefined,
      baseConfig: {
        header: ['分区名称', '供水量(m³)', '售水量(m³)', '产销差率(%)'],
        headerBGC: '#344b6e',
        oddRowBGC: '#344b6e',
        evenRowBGC: '#3a537b',
        data: [],
        index: true,
        indexHeader: '排名',
        columnWidth: [55, 120, 100, 100, 110],
        align: ['center', 'left', 'center', 'center', 'center']
      },
      zoneDfqList: [],
      nxDfqKpiConfig: {},
      nxDmaKpiConfig: {},
      zcDfqKpiConfig: {},
      zcDmaKpiConfig: {},
      dfqZoneData: [],
      dfqKpiData: [],
      dfqGroupKpiData: [],
      dmaZoneData: [],
      dmaKpiData: [],
      dmaKpiStatistic: [
        {color: '#3cdf73', count: 0, tips: '产销差率 < 10%'},
        {color: '#ffd400', count: 0, value: 10, tips: '10% <= 产销差率 < 20%'},
        {color: '#ff9900', count: 0, value: 20, tips: '20% <= 产销差率 < 30%'},
        {color: '#e9605d', count: 0, value: 30, tips: '产销差率 >= 30%'},
      ],
      terminalDataList: [],
      baseOption: {
        backgroundColor: '',
        color: colors,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          top: '10%',
          right: '8%',
          bottom: '12%',
          left: '18%',
          containsLabel: true,
          // show: true,
          // backgroundColor: '#FF0'
        },
        legend: {
          textStyle: {
            color: "#fff"
          },
          data: ['供水量(m³)', '售水量(m³)', '产销差率(%)']
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            color: '#FFFFFF',
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(191, 191, 191, 0.2)'
            }
          },
          data: []
        },
        yAxis: [
          {
            type: 'value',
            alignTicks: true,
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              color: '#FFFFFF',
              formatter: '{value} m³'
            }
          },
          {
            type: 'value',
            position: 'right',
            alignTicks: true,
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            // axisLine: {
            //   show: true,
            //   lineStyle: {
            //     color: colors[2]
            //   }
            // },
            axisLabel: {
              color: '#FFFFFF',
              formatter: '{value} %'
            }
          },
        ],
        series: [
          {
            name: '供水量(m³)',
            type: 'bar',
            data: []
          },
          {
            name: '售水量(m³)',
            type: 'bar',
            data: []
          },
          {
            name: '产销差率(%)',
            type: 'line',
            yAxisIndex: 1,
            data: []
          }
        ]
      },
    }
  },
  methods: {
    initChart() {
      this.nxWaterSupplyChart = echarts.init(document.getElementById('nx-water-supply-chart'), 'macarons')
      this.nxWaterSupplyChart.setOption(this.baseOption)
      this.zcWaterSupplyChart = echarts.init(document.getElementById('zc-water-supply-chart'), 'macarons')
      this.zcWaterSupplyChart.setOption(this.baseOption)
    },
    handleMapLoaded(scene) {
      this.mapScene = scene
      this.terminalMarkerLayer = new MarkerLayer();
      this.examineTerminalMarkerLayer = new MarkerLayer();
      this.dyhTerminalMarkerLayer = new MarkerLayer();
      this.drawPipeNetwork()
    },
    handlePolygonLayersVisibleChange(val) {
      if (val) {
        this.polygonLayers.forEach(layer => {
          layer.show()
        })
      } else {
        this.polygonLayers.forEach(layer => {
          layer.hide()
        })
      }
    },
    handlePipeNetworkVisibleChange(val) {
      if (val) {
        this.pipeNetworkLayers.forEach(layer => {
          layer.show()
        })
      } else {
        this.pipeNetworkLayers.forEach(layer => {
          layer.hide()
        })
      }
    },
    handleExamineTerminalMarkerVisibleChange(val) {
      if (val) {
        this.addTerminalMarkerToMap()
      } else {
        this.examineTerminalMarkerLayer.clear()
      }
    },
    handleDyhTerminalMarkerVisibleChange(val) {
      if (val) {
        this.addTerminalMarkerToMap()
      } else {
        this.dyhTerminalMarkerLayer.clear()
      }
    },
    onWindowResize() {
      // 利用屏幕分辨率和window对象的内高度来判断兼容IE
      let winFlag = window.innerHeight === window.screen.height
      // 利用window全屏标识来判断 -- IE无效
      let isFull = window.fullScreen || document.webkitIsFullScreen

      if (isFull === undefined) {
        this.isFullscreen = winFlag
      } else {
        this.isFullscreen = winFlag || isFull
      }
    },
    loadMonitorTerminals() {
      getZoneJoinTerminals({terminalMark: 1}).then((res => {
        this.terminalDataList = res.rows
      }))
    },
    addTerminalMarkerToMap() {
      const that = this
      const terminals = this.terminalDataList.filter(item => item.lat != null && item.lng != null)
      let point
      if (this.examineTerminalMarkerLayer) {
        this.examineTerminalMarkerLayer.clear()
      }
      if (this.dyhTerminalMarkerLayer) {
        this.dyhTerminalMarkerLayer.clear()
      }
      terminals.forEach(t => {
        point = [parseFloat(t.lng), parseFloat(t.lat)]

        const markerIcon = t.hookType === 1 ? `/images/terminal.png` : `/images/senior.png`
        const markerContent = `<div><img src="${markerIcon}" style="width: 40px;height: 40px;"></div>`
        let el = document.createElement('div')
        el.innerHTML = markerContent
        const marker = new Marker({element: el, draggable: false, offsets: [0, 0]}).setLnglat({
          lng: parseFloat(t.lng),
          lat: parseFloat(t.lat)
        })

        const data = t.realtimeGatherData
        const popup = new Popup({
          title: t.terminalName,
          lngLat: {
            lng: parseFloat(t.lng),
            lat: parseFloat(t.lat)
          },
          offsets: [0, 40],
          closeButton: false,
          html: `<div>
                  <div>瞬时流量：${data && data.instantNumber != null ? '<span style="color: limegreen;">' + data.instantNumber + '</span> m³/h' : '<span style="color: red;">-<span>'}</div>
                  <div>累计流量：${data && data.totalFlow != null ? '<span style="color: limegreen;">' + data.totalFlow + '</span> m³' : '<span style="color: red;">-<span>'}</div>
                  <div>压&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;力：${data && data.pressure != null ? '<span style="color: limegreen;">' + data.pressure + '</span> MPa' : '<span style="color: red;">-<span>'}</div>
                  <div>信号强度：${data && data.terminalCSQ != null ? '<span style="color: limegreen;">' + data.terminalCSQ + '</span>' : '<span style="color: red;">-<span>'}</div>
                  <div>更新时间：${data && data.ReadDate != null ? '<span style="color: limegreen;">' + data.ReadDate + '</span>' : '<span style="color: red;">-<span>'}</div>
                </div>`,
        });
        marker.setPopup(popup)

        // marker.on('click', (e) => {
        //   e.preventDefault()
        //   e.stopPropagation()
        //   this.examineTerminalMarkerLayer.getMarkers().forEach(m => m.closePopup())
        //   this.dyhTerminalMarkerLayer.getMarkers().forEach(m => m.closePopup())
        //   marker.openPopup()
        // })

        marker.on('mouseover', (e) => {
          marker.openPopup()
        })

        marker.on('mouseout', (e) => {
          marker.closePopup()
        })

        if (t.hookType === 1) {
          this.examineTerminalMarkerLayer.addMarker(marker);
        } else {
          this.dyhTerminalMarkerLayer.addMarker(marker);
        }
      })
      this.mapScene.addMarkerLayer(this.examineTerminalMarkerLayer);
      this.mapScene.addMarkerLayer(this.dyhTerminalMarkerLayer);

      if (!this.examineTerminalMarkerVisible) {
        this.examineTerminalMarkerLayer.hide()
      }
      if (!this.dyhTerminalMarkerVisible) {
        this.dyhTerminalMarkerLayer.hide()
      }
    },
    loadOverviewData(id) {
      getZCOverviewData({zbz1: id}).then(res => {
        const data = res.data
        this.assetsOptions.forEach(item => {
          item.value = data[item.key]
        })
        // this.overviewAnnualOptions.forEach(item => {
        //   item.value = data[item.key]
        // })
        if (id === "4401180006") {
          this.zcOverviewMonthlyOptions.forEach(item => {
            item.value = data[item.key]
            item.tbRate = data[item.key + 'Tb']
            item.hbRate = data[item.key + 'Hb']
          })
        } else {
          this.nxOverviewMonthlyOptions.forEach(item => {
            item.value = data[item.key]
            item.tbRate = data[item.key + 'Tb']
            item.hbRate = data[item.key + 'Hb']
          })
        }
      })
    },
    loadAllDfqKpiData() {
      getDfqKpiData().then(res => {
        const {dfq, kpi} = res.data
        const data1 = []
        const data2 = []
        const kpiData = []

        kpi.forEach(item => {
          const dfqZone = dfq.filter(d => d.areaID === item.zbz1)
          const dfqInfo = dfqZone[0]
          if (item.zbz1.startsWith('4401180006')) {
            data1.push([dfqInfo.areaName, item.zbz4, item.zbz5, item.zbz7])
          } else {
            data2.push([dfqInfo.areaName, item.zbz4, item.zbz5, item.zbz7])
          }
          kpiData.push({
            id: dfqInfo.areaID,
            name: dfqInfo.areaName,
            areaPoint: dfqInfo.areaPoint,
            month: item.zbz3,
            supply: item.zbz4,
            sale: item.zbz5,
            free: item.zbz6,
            rate: item.zbz7,
          })
        })

        this.zcDfqKpiConfig = Object.assign({}, this.baseConfig)
        this.zcDfqKpiConfig.data = data1
        this.nxDfqKpiConfig = Object.assign({}, this.baseConfig)
        this.nxDfqKpiConfig.data = data2

        this.dfqZoneData = dfq
        this.dfqKpiData = kpiData

        setTimeout(() => {
          this.drawDfqToMap()
        }, 1000)
      })
    },
    loadDfqKpiData(id) {
      getDfqKpiData({zbz1: id}).then(res => {
        const {group, dfq, kpi} = res.data
        const data = []
        const kpiData = []

        kpi.forEach(item => {
          const dfqZone = dfq.filter(d => d.areaID === item.zbz1)
          const dfqInfo = dfqZone[0]
          // data.push([dfqInfo.areaName, item.zbz4, item.zbz5, item.zbz7])
          // kpiData.push({
          //   id: dfqInfo.areaID,
          //   name: dfqInfo.areaName,
          //   areaPoint: dfqInfo.areaPoint,
          //   month: item.zbz3,
          //   supply: item.zbz4,
          //   sale: item.zbz5,
          //   free: item.zbz6,
          //   rate: item.zbz7,
          // })
        })

        // if (id === '4401180006') {
        //   this.zcDfqKpiConfig = Object.assign({}, this.baseConfig)
        //   this.zcDfqKpiConfig.data = data
        // } else {
        //   this.nxDfqKpiConfig = Object.assign({}, this.baseConfig)
        //   this.nxDfqKpiConfig.data = data
        // }

        // this.dfqKpiData = kpiData
        this.dfqGroupKpiData = group

        this.makeChartData(id)
      })
    },
    loadDMAKpiData() {
      getDMAKpiData().then(res => {
        const {dma, kpi} = res.data
        const data1 = []
        const data2 = []
        const kpiData = []

        kpi.forEach(item => {
          const dmaZone = dma.filter(d => d.areaID === item.zbz1)
          const dmaInfo = dmaZone[0]
          if (item.zbz1.startsWith('4401180006')) {
            data1.push([dmaInfo.areaName, item.zbz4, item.zbz5, item.zbz7])
          } else {
            data2.push([dmaInfo.areaName, item.zbz4, item.zbz5, item.zbz7])
          }
          kpiData.push({
            id: dmaInfo.areaID,
            name: dmaInfo.areaName,
            areaPoint: dmaInfo.areaPoint,
            month: item.zbz3,
            supply: item.zbz4,
            sale: item.zbz5,
            free: item.zbz6,
            rate: item.zbz7,
          })
        })

        this.zcDmaKpiConfig = Object.assign({}, this.baseConfig)
        this.zcDmaKpiConfig.data = data1
        this.nxDmaKpiConfig = Object.assign({}, this.baseConfig)
        this.nxDmaKpiConfig.data = data2

        this.dmaZoneData = dma
        this.dmaKpiData = kpiData
        setTimeout(() => {
          this.drawDmaToMap()
        }, 1000)
      })
    },
    getKpiRateColor(rate) {
      const colors = this.dmaKpiStatistic.map(item => item.color)
      const fRate = parseFloat(rate)
      if (fRate < 10) {
        return colors[0]
      } else if (fRate <= 10 && fRate < 20) {
        return colors[1]
      } else if (fRate <= 20 && fRate < 30) {
        return colors[2]
      } else {
        return colors[3]
      }
    },
    makeChartData(id) {
      const option = Object.assign({}, this.baseOption)

      const xAxisData = Object.keys(this.dfqGroupKpiData)
      xAxisData.sort()
      option.xAxis.data = xAxisData

      const series1 = [], series2 = [], series3 = []
      xAxisData.forEach(m => {
        const dataList = this.dfqGroupKpiData[m]
        const supply = sumByKey(dataList.filter(item => item.zbz1 === id), 'zbz4')
        series1.push(supply)
        const sale = sumByKey(dataList.filter(item => item.zbz1 === id), 'zbz5')
        series2.push(sale)
        const rate = (sumByKey(dataList.filter(item => item.zbz1 === id), 'zbz7') / dataList.length).toFixed(2)
        series3.push(rate)
      })
      option.series[0].data = series1
      option.series[1].data = series2
      option.series[2].data = series3

      if (id === '4401180006') {
        this.zcWaterSupplyChart.setOption(option)
      } else {
        this.nxWaterSupplyChart.setOption(option)
      }
    },
    handleCurrentDfqChange(val) {
      this.selectedDfq = val;
      this.loadDMAKpiData()
    },
    handleKpiDetailClick(type) {
      let path = ''
      if (type === 'dfq') {
        path = '/kpi/freezeDfq'
      } else {
        path = '/kpi/freezeDma'
      }

      // 本页面打开
      this.$router.push({path: path})

      // 新页面打开
      // let routeData = this.$router.resolve({
      //   path: path
      // })
      // window.open(routeData.href, '_blank')
    },
    addPolygonLayer(scene, coords, color, id, name, rate, zIndex = 10, isDma = false) {
      const source = {
        type: 'FeatureCollection',
        features: [
          {
            type: 'Feature',
            properties: {
              name: name,
              rate: rate
            },
            geometry: {
              type: 'Polygon',
              coordinates: coords,
            },
          },
        ],
      }

      const layer = new PolygonLayer({name: id, zIndex: zIndex})
        .source(source)
        .color(color)

      if (isDma) {
        layer.active(true)
          .style({
            opacity: 0.9,
          });
      } else {
        layer.style({
          opacity: 0.3,
        });
      }

      const layer2 = new LineLayer({
        zIndex: zIndex + 1
      }).source(source)
        .color('#d71f97')
        .size(2)
      // .style({
      //   lineType: 'dash',
      //   dashArray: [2, 2],
      // });
      scene.addLayer(layer2);

      layer.on('mousemove', e => {
        const popup = new Popup({
          offsets: [0, 0],
          closeButton: false,
          closeOnClick: true,
        }).setLnglat(e.lngLat).setHTML(`<span>${e.feature.properties.name}</span><br/><span>产销差率: ${e.feature.properties.rate}%</span>`);
        scene.addPopup(popup);
      });

      // const textlayer = new PolygonLayer({zIndex: zIndex + 1})
      //     .source(source)
      //     .color('#FFFFFF')
      //     .shape('name', 'text')
      //     .size(18)
      //     .style({
      //       textAnchor: 'center', // 文本相对锚点的位置 center|left|right|top|bottom|top-left
      //       textOffset: [0, 0], // 文本相对锚点的偏移量 [水平, 垂直]
      //       spacing: 2, // 字符间距
      //       padding: [1, 1], // 文本包围盒 padding [水平，垂直]，影响碰撞检测结果，避免相邻文本靠的太近
      //       stroke: '#ffffff', // 描边颜色
      //       strokeWidth: 0.3, // 描边宽度
      //       strokeOpacity: 1.0
      //     });
      // scene.addLayer(textlayer);

      // const centerCoords = []
      // centerCoords.push(JSON.parse(this.dfqZoneData[0].areaPoint))
      // const turfPolygon = turf.polygon(centerCoords);
      // const centroid = turf.centroid(turfPolygon);
      // const centerPoint = centroid.geometry.coordinates

      // layer.on('mousemove', e => {
      // const popup = new Popup({
      //   offsets: [0, 0],
      //   closeButton: false,
      //   // closeOnClick: true,
      // }).setLnglat([centerPoint[0], centerPoint[1]]).setHTML(`<span>${name}</span><br/><span>产销差率(%): ${rate}</span>`);
      // // scene.addPopup(popup);
      // // });
      //
      // layer.on('click', (ev) => {
      //   popup.setLngLat(ev.lngLat)
      //   scene.addPopup(popup);
      //   popup.open()
      // }); // 鼠标左键点击图层事件

      this.layerOriginColorMap[id] = color

      this.polygonLayers.push(layer)
      this.polygonLayers.push(layer2)
      scene.addLayer(layer)
    },
    drawDfqToMap() {
      if (this.dfqZoneData.length) {
        const that = this
        let zIndex = 10
        this.dfqZoneData.forEach(dfq => {
          if (dfq.areaPoint) {
            that.zoomAndCenterMap(dfq)
            const coordinates = []
            coordinates.push(JSON.parse(dfq.areaPoint))
            const rate = this.dfqKpiData.filter(item => item.id === dfq.areaID)[0].rate
            const color = this.getKpiRateColor(rate)
            this.addPolygonLayer(that.mapScene, coordinates, color, dfq.areaID, dfq.areaName, rate, zIndex, false)
            // this.addPolygonLayer(that.mapScene, coordinates, color, dfq.areaID, `${dfq.areaName}\n漏损率：${rate}%`, rate, zIndex, false)
            zIndex += 1
          }
        })
      }
    },
    drawDmaToMap() {
      if (this.dmaZoneData.length) {
        const that = this
        let zIndex = 20000
        this.dmaZoneData.forEach(dma => {
          if (dma.areaPoint) {
            that.zoomAndCenterMap(dma)
            const coordinates = []
            coordinates.push(JSON.parse(dma.areaPoint))
            const rate = this.dmaKpiData.filter(item => item.id === dma.areaID)[0].rate
            const color = this.getKpiRateColor(rate)
            this.addPolygonLayer(that.mapScene, coordinates, color, dma.areaID, dma.areaName, rate, zIndex, true)
            // this.addPolygonLayer(that.mapScene, coordinates, color, dma.areaID, `${dma.areaName}\n漏损率：${rate}%`, rate, zIndex, true)
            zIndex += 1
          }
        })
      }
    },
    zoomAndCenterMap(zone) {
      if (zone.areaPoint && !this.mapCenterFocused) {
        const coords = []
        coords.push(JSON.parse(zone.areaPoint))
        const turfPolygon = turf.polygon(coords);
        const centroid = turf.centroid(turfPolygon);
        const centerPoint = centroid.geometry.coordinates
        this.mapScene.setCenter([centerPoint[0], centerPoint[1]])
        this.mapCenterFocused = true
      }
    },
    getTerminalsWithPosition() {
      return this.terminalDataList.filter(item => item.lat != null && item.lng != null)
    },
    handleHomeIconClick() {
      window.open('/index', '_blank')
    },
    drawPipeNetwork() {
      const url1 = 'http://139.9.155.246:8088/geoserver/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&STYLES&LAYERS=zengcheng:zhucun2_pipe&exceptions=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A4326&WIDTH=521&HEIGHT=768&BBOX={bbox}'
      const layer1 = drawWmsLayer(this.mapScene, url1)
      layer1.color('red'); // 常量颜色
      this.pipeNetworkLayers.push(layer1)
      const url2 = 'http://139.9.155.246:8088/geoserver/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&STYLES&LAYERS=zengcheng:ningxi2_pipe&exceptions=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A4326&WIDTH=521&HEIGHT=768&BBOX={bbox}'
      this.pipeNetworkLayers.push(drawWmsLayer(this.mapScene, url2))
    },
    bodyScale() {
      const deviceWidth = document.body.clientWidth
      const deviceHeight = document.body.clientHeight
      const scaleW = deviceWidth / 1920
      const scaleH = deviceHeight / 1080
      document.getElementById('zcbi-toolbar').style.zoom = scaleW > scaleH ? scaleH : scaleW
      document.getElementById('zcbi-header1').style.zoom = scaleW > scaleH ? scaleH : scaleW
      document.getElementById('zcbi-header2').style.zoom = scaleW > scaleH ? scaleH : scaleW
      document.getElementById('zcbi-box1').style.zoom = scaleW > scaleH ? scaleH : scaleW
      document.getElementById('zcbi-box2').style.zoom = scaleW > scaleH ? scaleH : scaleW
      // document.body.style.zoom = scaleW > scaleH ? scaleH : scaleW
    }
  },
  created() {
    // this.bodyScale()
  },
  computed: {
    store() {
      return store
    },
    getAvailableBottom() {
      return {bottom: this.screenBottom + 'px'}
    }
  },
  watch: {
    isFullscreen(val) {
      if (!val) {
        this.screenBottom = 95
      } else {
        this.screenBottom = 10
      }
    }
  },
  mounted() {
    setTimeout(() => {
      this.initChart()
      this.loadOverviewData("4401180006")
      this.loadOverviewData("4401180007")
      this.loadDfqKpiData("4401180006")
      this.loadDfqKpiData("4401180007")
      this.loadAllDfqKpiData()
      this.loadDMAKpiData()
      this.loadMonitorTerminals()
      this.bodyScale()
    }, 500)
    // this.timerHandler = setInterval(() => {
    //   this.currentTime = new moment().format('YYYY年MM月DD日 HH:mm:ss')
    // }, 1000)

    // window.addEventListener('resize', this.onWindowResize)

    const designWidth = 1920
    const designHeight = 1080

    // autoFit.init({
    //   designWidth: designWidth,
    //   designHeight: designHeight,
    //   renderDom: '#app',
    //   resize: true
    // }, true) // 可关闭控制台运行提示输出

    // autoFit.init({
    //   designWidth: designWidth,
    //   designHeight: designHeight,
    //   renderDom: '#zcbi-box2',
    //   resize: true
    // }, true) // 可关闭控制台运行提示输出

    window.addEventListener('resize', () => {
      this.bodyScale()
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onWindowResize)
  },
  beforeRouteLeave(to, from, next) {
    clearInterval(this.timerHandler)
    next()
  }
}
</script>

<style scoped lang="scss">
.header {
  position: absolute;
  top: 0;
  width: 100%;
  height: 171px;
  text-align: center;
  background-image: url("../../../assets/leakage/bi/mask_top.png");
  background-size: 100% 171px;
  background-repeat: no-repeat;
  z-index: 10000;

  .bg {
    width: 100%;
    height: 66px;
    text-align: center;
    background-image: url("../../../assets/leakage/bi/header_bg.png");
    background-size: 100% 66px;
    background-repeat: no-repeat;
  }

  .header-home {
    color: #FFFFFF;
    position: fixed;
    right: 10%;
    top: 22px;
    font-size: 18px;
    cursor: pointer;
    width: 138px;
    height: 39px;
    text-align: center;
    line-height: 39px;
    background-image: url("../../../assets/leakage/bi/out_bg.png");
  }
}

.header-foot {
  width: 17.6%;
  height: 48px;
  position: fixed;
  left: 39.9%;
  top: 60px;
  color: #FFFFFF;
  z-index: 11000;
  text-align: center;
  font-size: 18px;
  padding-top: 12px;
  letter-spacing: 4px;
  background-image: url("../../../assets/leakage/bi/header_foot.png");
  background-size: 100% 100%;
}

.box-container {
  width: 500px;
  margin-bottom: 8px;
  position: relative;
  border: 1px solid #17366c;
  //background: linear-gradient(to left, #3897cf, #3897cf) left top no-repeat, linear-gradient(to bottom, #3897cf, #3897cf) left top no-repeat,
  //linear-gradient(to left, #3897cf, #3897cf) right top no-repeat, linear-gradient(to bottom, #3897cf, #3897cf) right top no-repeat,
  //linear-gradient(to left, #3897cf, #3897cf) left bottom no-repeat, linear-gradient(to bottom, #3897cf, #3897cf) left bottom no-repeat,
  //linear-gradient(to left, #3897cf, #3897cf) right bottom no-repeat, linear-gradient(to left, #3897cf, #3897cf) right bottom no-repeat;
  //background-size: 1px 20px, 20px 1px, 1px 20px, 20px 1px;
  //background-color: rgba(0, 0, 0, 0.1);
  background-color: #17366c;

  .box-head {
    color: #FFFFFF;
    font-size: 18px;
    padding: 7px 0 0 20px;

    &::before {
      position: absolute;
      top: 10px;
      left: 10px;
      width: 4px;
      height: 20px;
      background: red;
      content: " ";
    }
  }

  .custom-btn {
    width: 80px;
    height: 24px;
    color: #FFFFFF;
    background: none;
    margin-right: 10px;
    cursor: pointer;
    border: 1px solid rgb(0, 174, 255);
    z-index: 1000;
    font-size: 14px;

    &:active {
      background-color: rgb(19, 166, 224);
    }
  }

  .custom-btn-active {
    background-color: rgb(19, 166, 224);
  }
}

::v-deep .el-drawer__body {
  background-color: #344b6e !important;
  overflow-y: hidden;
}

::v-deep .el-drawer__header {
  background-color: #344b6e !important;
  margin-bottom: 0 !important;
  color: #FFFFFF;
  padding: 12px;
  padding-bottom: 0;
}

::v-deep .el-table__body-wrapper {
  background: #344b6e !important;
}

// 表格行选中时高亮样式
::v-deep .el-table__body tr.current-row > td {
  background: #18407d !important;
}

/* 表格鼠标悬浮时的样式（高亮） */
::v-deep .el-table--enable-row-hover .el-table__body tr:hover {
  background-color: #344b6e !important;
}

/*表格鼠标悬停的样式（背景颜色）*/
::v-deep .el-table tbody tr:hover > td {
  background-color: #18407d !important;
}

/*表格鼠标悬停的样式（背景颜色）*/
::v-deep .el-table__body .el-table__row.hover-row td {
  background-color: #18407d !important;
}

::v-deep .l7-popup-content {
  background-color: #3a537b !important;
}

::v-deep .l7-popup-content__title {
  color: #FFFFFF !important;
}

::v-deep .l7-popup-content__panel {
  color: #FFFFFF !important;
}

::v-deep .l7-popup .l7-popup-content {
  position: relative;
  padding: 16px;
  font-size: 14px;
  color: #FFFFFF;
  background: #5e72af;
  border-radius: 3px;
  -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

::v-deep .l7-popup-anchor-bottom .l7-popup-tip {
  -webkit-align-self: center;
  -ms-flex-item-align: center;
  align-self: center;
  border-top-color: #5e72af;
  border-bottom: none;
}
</style>
